<?php
// +----------------------------------------------------------------------
// | Author: 
// +----------------------------------------------------------------------

namespace app\wechat\controller;
use think\Session;
use thirdapi\tp_wechat\Wechat;
use com\Wxpay;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class StoreAdminController extends AuthController {

    private $model;
    private $store_id;
    private $userModel;
    private $orderModel;
    private $storeAdminInfo;
    private $storeInfo;
    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->model = model('StoreAdmin');
        $this->orderModel = model('Order');
        $this->userModel = model('User');
        $user_info = Session::get('user_info','html5');
        if(!Session::has('user_info','html5') && empty($this->open_id)){
            $this->error('未知错误，请联系管理员');
            exit;
        }
        if(!$user_info && !empty($this->open_id)){
            $user_info = db('User')->where(['openid'=>$this->open_id])->find();
            Session::set('user_info',$user_info,'html5');
        }

        $this->storeAdminInfo = $this->model->where(['user_id'=>$user_info['id']])
        ->alias('ss')
        ->join('__STORE__ st','ss.store_id=st.id','LEFT')
        ->field('ss.*,st.name as store_name')
        ->find();
        if(!$this->storeAdminInfo){
            $this->error('未知错误，请联系管理员');
            exit;
        }

        $this->store_id = $this->storeAdminInfo['store_id'];
        
        $where = [];
        $where['gs.is_on_sale'] = 1;
        $where['gs.store_id'] = $this->store_id;
        $goodsStoreFields = 'gs.id as id,gs.sale_mode as sale_mode,gs.store_id as store_id,gs.type_id as type_id,gs.hire_sum as hire_sum,gs.amount_sum as amount_sum,gs.goods_id as goods_id,gs.store_count as store_count,gs.sales_sum as sales_sum,gs.is_on_sale as is_on_sale,gs.sort as sort,';
        $goodsFields = 'g.goods_name as goods_name,g.image as image,g.give_integral as give_integral,';
        $typeItemFields = 'ti.price as price,ti.vip_price as vip_price,ti.hire_price as hire_price,ti.deposit_amount as deposit_amount';
        $goodsStoreList = db('GoodsStore')->alias('gs')
        ->field($goodsStoreFields.$goodsFields.$typeItemFields.',gt.name as cate_name')
        ->join('__GOODS_TYPE__ gt','gt.id=gs.type_id','LEFT')
        ->join('__TYPE_ITEM__ ti','ti.type_id=gs.type_id and ti.goods_id=gs.goods_id','LEFT')
        ->join('__GOODS__ g','g.id=gs.goods_id','LEFT')
        ->where($where)
        ->order('gs.sort asc')
        ->select();
        $saAccouont = db('StoreAccount')->where(['store_id'=>$this->store_id])->find();
        $this->assign([
            'goodsStoreList' => $goodsStoreList,
            'saAccountInfo' => $saAccouont,
            'storeAdminInfo' => $this->storeAdminInfo
        ]);
    }
    /**
     * 门店管理首页
     */
    public function index(){
        return $this->fetch('index');
    }

    /**
     * 发货
     */
    public function order_shipping(){
        $json = [
            'status' => 0,
            'msg' =>'订单不存在'
        ];
        $order_id = input('order_id');
        $where['order_id'] = $order_id;
        $where['order_status'] = 2;
        $where['shipping_status'] = 0;
        $orderInfo = $this->orderModel->where($where)->find();
        if($orderInfo && $orderInfo['order_id']>0){
            $data['order_status'] = 3;
            $data['shipping_status'] = 1;
            $data['hire_status'] = $orderInfo['hire_status'];
            if($orderInfo['order_mode'] == 1){
                $data['order_status'] = 3;
                $data['hire_status'] = 2;
                $data['start_time'] = time();
            }
            if($this->orderModel->where($where)->update($data)){
                db('OrderAction')->insert(['order_id'=>$order_id,
                        'action_user'=>$orderInfo['user_id'],
                        'order_status'=>$data['order_status'],
                        'shipping_status'=>1,
                        'pay_status'=>1,
                        'action_note'=>'确认发货成功',
                        'log_time'=>time(),
                        'status_desc'=>'确认发货']);
                $json['status'] = 1;
                $json['msg'] = '确认发货成功';
            }else{
                $json['msg'] = '发货失败';
            }
        }
        echo json_encode($json);
        exit;
    }

    /**
     * 客户签收
     */
    public function order_sign(){
        $json = [
            'status' => 0,
            'msg' =>'订单不存在'
        ];
        $order_id = input('order_id');
        $where['order_id'] = $order_id;
        $where['order_status'] = 3;
        $where['shipping_status'] = 1;
        $orderInfo = $this->orderModel->where($where)->find();
        if($orderInfo && $orderInfo['order_id']>0){
            $data['order_status'] = 5;
            $data['shipping_status'] = 1;
            $data['hire_status'] = $orderInfo['hire_status'];
            if($orderInfo['order_mode'] == 1){
                $data['order_status'] = 4;
                $data['hire_status'] = 2;
                $data['start_time'] = time();
                $data['end_time'] = time()+24*3600;
            }
            if($this->orderModel->where($where)->update($data)){
                db('OrderAction')->insert(['order_id'=>$order_id,
                        'action_user'=>$orderInfo['user_id'],
                        'order_status'=>$data['order_status'],
                        'shipping_status'=>1,
                        'pay_status'=>1,
                        'action_note'=>'确认客户签收货物',
                        'log_time'=>time(),
                        'status_desc'=>'确认签收']);
                $json['status'] = 1;
                $json['msg'] = '确认签收成功';
            }else{
                $json['msg'] = '确认签收失败';
            }
        }
        echo json_encode($json);
        exit;
    }
    /**
     * 我的二维码
     */
    public function myqrcode(){
        $redirectUrl = $this->storeAdminInfo['short_url'];
        $redirectHUrl = $this->storeAdminInfo['hire_short_url'];
        $this->assign([
            'redirectUrl' => $redirectUrl,
            'redirectHUrl' => $redirectHUrl
        ]);
        return $this->fetch('myqrcode');
    }
    /**
     * 退换处理
     */
    public function returns_index(){
        $keyword = input('keyword');
        if($keyword !== ''){
            $where['o.order_sn'] = ['like','%'.$keyword.'%'];
        }
        $where['o.store_id'] = $this->store_id;
        $where['o.order_mode'] = 1;
        $where['o.order_status'] = ['>=','2'];
        $where['o.hire_status'] = ['>=','1'];

        $list = $this->orderModel->where($where)
        ->alias('o')
        ->join('__STORE__ ss','o.store_id=ss.id','LEFT')
        ->join('__STORE_SEAT__ st','o.seat_id=st.id','LEFT')
        ->field('o.*,ss.name as store_name,st.seat_num as seat_num')
        ->order('o.order_id desc,o.order_status asc')
        ->paginate(10,false,['query' => request()->param()]);
        $page = $list->render();
        
        $this->assign([
            'list' => $list,
            'page' => $page
        ]);
        return $this->fetch('returns_index');
    }

    /*
     * 通过归还操作
    */
    public function refundorder(){
        $json = [
            'status' => 0,
            'msg' =>'订单不存在或未进入归还审核状态'
        ];
        $openid = '';
        if(Session::has('user_info','html5')){
            $openid = Session::get('user_info','html5')['openid'];
        }
        $user_info = $this->userModel->where(['openid'=>$openid])->find();
        $order_id = input('order_id');

        $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
        if($orderInfo){
            if($orderInfo['order_mode'] == 1 && $orderInfo['order_status'] == 4 && $orderInfo['hire_status'] == 3 && $orderInfo['audit_status'] == 0){
                $data = [];
                $data['order_status'] = 4;
                $data['hire_status'] = 4;
                $data['refund_status'] = 1;
                $data['audit_status'] = 1;
                if($this->orderModel->where(['order_id'=>$order_id])->update($data)){
                    db('OrderAction')->insert(['order_id'=>$order_id,
                    'action_user'=>$user_info['id'],
                    'order_status'=>1,
                    'shipping_status'=>1,
                    'pay_status'=>1,
                    'action_note'=>'通过归还审核',
                    'log_time'=>time(),
                    'status_desc'=>'归还审核']);
                    $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
                    if($orderInfo['audit_status'] == 1 && $orderInfo['refund_status'] == 1){
                        $json = $this->refundFun($orderInfo);
                        echo json_encode($json);
                        exit;
                    }
                }
            }
        }
        echo json_encode($json);
        exit;
    }

    /*
     * 退款操作
    */
    public function order_refund(){
        $json = [
            'status' => 0,
            'msg' =>'订单已经退款成功'
        ];
        $order_id = input('order_id');
        $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
        if($orderInfo && $orderInfo['audit_status'] == 1 && $orderInfo['refund_status'] <= 1){
            $json = $this->refundFun($orderInfo);
            echo json_encode($json);
            exit;
        }
        echo json_encode($json);
        exit;
    }

    /**
     * 订单退款
    */
    private function refundFun($orderInfo){
        $json = [
            'status' => 0,
            'msg' =>'订单已经退款成功'
        ];
        $order_id = $orderInfo['order_id'];
        $wx_config = db('WxAccount')->where(['appid'=>$orderInfo['appid']])->find();
        $orderData = [];
        $out_refund_no = 'ecr'.date('YmdHis',time()).mt_rand(1000,9999);
        if($orderInfo['audit_status'] == 1 && $orderInfo['refund_status'] <= 1){
            if($this->orderModel->where(['order_id'=>$order_id])->update(['out_refund_no'=>$out_refund_no])){
                $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
                $orderData = [
                    'transaction_id' => $orderInfo['transaction_id'],
                    'refund_no' => $out_refund_no,
                    'remark' => '客户申请退单',
                    'order_no' => $orderInfo['order_sn'],
                    'amount' => $orderInfo['total_amount'],
                    'notify_url' => 'http://'.$_SERVER['HTTP_HOST'].Url('Order/refundSuccess')
                ];
                $orderData['appid'] = $wx_config['appid'];
                $orderData['appsecret'] = $wx_config['appsecret'];
                $orderData['mchid'] = $wx_config['mchid'];
                $orderData['mchkey'] = $wx_config['mchkey'];
                $wxpay = new Wxpay($wx_config);
                $wxpay->wx_config = $wx_config;
                $result = $wxpay->refundOrder($orderData);
                if($result['return_code'] == 'SUCCESS'){
                    $newData = [];
                    $newData['refund_id'] = $result['refund_id'];
                    $newData['refund_time'] = time();
                    $newData['refund_fee'] = $orderInfo['total_amount'];
                    $newData['hire_status'] = 5;
                    $newData['order_status'] = 5;
                    $newData['refund_status'] = 2;
                    $newData['end_time'] = time();
                    
                    if($this->orderModel->where(['order_id'=>$order_id])->update($newData)){
                        db('OrderAction')->insert(['order_id'=>$order_id,
                                'action_user'=>$orderInfo['user_id'],
                                'order_status'=>2,
                                'shipping_status'=>0,
                                'pay_status'=>1,
                                'action_note'=>'您支付了订单',
                                'log_time'=>time(),
                                'status_desc'=>'支付订单']);
                        $orderGoods = db('OrderGoods')->where(['order_id'=>$order_id])->select();
                        foreach($orderGoods as $item){
                            db('Goods')->where(['id'=>$item['goods_id']])->setInc('store_count',$item['goods_num']);
                            
                            if($orderInfo['store_id'] != $orderInfo['return_store_id']){
                                db('GoodsStore')->where(['goods_id'=>$item['goods_id'],'store_id'=>$orderInfo['return_store_id']])->setInc('store_count',$item['goods_num']);
                            }
                            db('Goods')->where(['id'=>$item['goods_id']])->setDec('hire_sum',$item['goods_num']);
                            if($orderInfo['store_id'] == $orderInfo['return_store_id']){
                                db('GoodsStore')->where(['id'=>$item['goods_store_id']])->setDec('hire_sum',$item['goods_num']);
                            }                       
                            if($orderInfo['store_id'] == $orderInfo['return_store_id']){
                                db('StoreAccount')->where(['id'=>$item['store_id']])->setDec('amount_sum',$item['goods_num']*$item['price']);
                                db('StoreAccount')->where(['id'=>$item['store_id']])->setDec('paied_amount',$item['goods_num']*$item['price']);
                            }
                        }
                        model('User')->where(['id'=>$orderInfo['user_id']])->setDec('consumption_price',$orderInfo['total_amount']);
                        
                        $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
                        $user_info = db('User')->where(['id'=>$orderInfo['user_id']])->find();
                        $this->sendReturnMsg($orderInfo,$user_info,'');
                        $json['status'] = 1;
                        $json['msg'] = '退换押金成功';
                        return $json;
                    }
                }
            }
        }
        return $json;
    }

    /*
     * 归还操作通知信息
    */
    private function sendReturnMsg($orderInfo,$user_info,$goods_names){
        try{
            $storeInfo = db('Store')->where(['id'=>$orderInfo['store_id']])->find();
            $messageData = [];
            $template_id = 'jUZlEruXNU9vZa-5UgNMe0V6bhdjFytPJ73x9D0pAFQ';
            if($orderInfo['audit_status'] == 1){
                //通知顾客
                $first = ['value' => '您好！您已成功归还一个烟杆：','color' => '#173177'];
                $keyword1 = ['value' => $storeInfo['name'],'color' => '#173177'];
                $keyword2 = ['value' => date('Y-m-d H:i:s',time()),'color' => '#173177'];
                $timeLen = (time()-$orderInfo['pay_time'])/3600;
                $keyword3 = ['value' => sprintf("%.2f",$timeLen<0.1?0.1:$timeLen).'小时','color' => '#173177'];
                $keyword4 = ['value' => $orderInfo['order_sn'],'color' => '#173177'];
                $remark = ['value' => '此次租借产生费用0元，已退还押金'.$orderInfo['total_amount'].'元。','color' => '#173177'];
                $messageData['first'] = $first;
                $messageData['keyword1'] = $keyword1;
                $messageData['keyword2'] = $keyword2;
                $messageData['keyword3'] = $keyword3;
                $messageData['keyword4'] = $keyword4;
                $messageData['remark'] = $remark;
            }else{
                //通知顾客
                $template_id = 'YnfvZxIpZz2RGRR-KV3QS3QBUOLzoEfn6Nk4HYB6zeM';
                $first = ['value' => '您好！您的烟杆归还申请审核结果通知：','color' => '#173177'];
                $keyword1 = ['value' => $storeInfo['name'],'color' => '#173177'];
                $keyword2 = ['value' => '不通过','color' => '#173177'];
                $keyword3 = ['value' => $orderInfo['audit_remark'],'color' => '#173177'];
                $remark = ['value' => '如有需要，请联系导购后再次提交申请','color' => '#173177'];
                
                $messageData['first'] = $first;
                $messageData['keyword1'] = $keyword1;
                $messageData['keyword2'] = $keyword2;
                $messageData['keyword3'] = $keyword3;
                $messageData['remark'] = $remark;
            }
            $wxAccount = db('WxAccount')->where(['appid'=>$orderInfo['appid']])->find();
            $baseUrl = 'http://'.$wxAccount['web_url'].Url('Store/returns');
            $natUrl = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$orderInfo['appid'].'&redirect_uri='.urlencode($baseUrl).'&response_type=code&scope=snsapi_base&state=123#wechat_redirect';
            $message = Wechat::message($this->options);
            $msgData = [
                'touser' => $user_info['openid'],
                'template_id' => $template_id,
                'appid' => $orderInfo['appid'],
                'data' => $messageData,
                'url' => $natUrl
            ];
            $result = $message->sendTemplateMessage($msgData);
            
            db('WxApi')->insert(['content'=>json_encode($msgData),'typename'=>'sendMessage']);
        }catch(Exception $e){
            db('WxApi')->insert(['content'=>json_encode($e),'typename'=>'error']);
        }  
    }

    /*
     * 驳回归还操作
    */
    public function rejectorder(){
        $openid = '';
        if(Session::has('user_info','html5')){
            $openid = Session::get('user_info','html5')['openid'];
        }
        $user_info = $this->userModel->where(['openid'=>$openid])->find();
        $order_id = input('order_id');

        $order_config = db('CommonEnum')->where(['mode_name'=>'订单配置','enum_name'=>'拒绝原因'])->find();
        $reject_remark = explode("\r\n",$order_config['remark']);

        $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
        if($orderInfo){
            if($orderInfo['order_mode'] == 1 && $orderInfo['order_status'] == 4 && $orderInfo['hire_status'] == 3 && $orderInfo['audit_status'] == 0){
                if(IS_POST){
                    $remark = input('reject_remark');
                    if($remark == '其他'){
                        $remark = input('other_remark');
                    }
                    $data = [];
                    $data['order_status'] = 4;
                    $data['hire_status'] = 3;
                    $data['refund_status'] = 0;
                    $data['audit_status'] = 2;
                    $data['audit_remark'] = $remark;
                    if($this->orderModel->where(['order_id'=>$order_id])->update($data)){
                        db('OrderAction')->insert(['order_id'=>$order_id,
                        'action_user'=>$user_info['id'],
                        'order_status'=>1,
                        'shipping_status'=>0,
                        'pay_status'=>0,
                        'action_note'=>'驳回归还审核',
                        'log_time'=>time(),
                        'status_desc'=>'归还审核']);

                        $orderInfo = $this->orderModel->where(['order_id'=>$order_id])->find();
                        $user_info = db('User')->where(['id'=>$orderInfo['user_id']])->find();
                        $this->sendReturnMsg($orderInfo,$user_info,'');
                        
                        $this->redirect('StoreAdmin/returns_index');
                        exit;
                    }
                }

                $this->assign([
                    'reject_remark' => $reject_remark,
                    'orderInfo' => $orderInfo
                ]);
                return $this->fetch('rejectorder');
                exit;
            }
        }
        
        $this->error('订单不存在或未进入归还审核状态',Url('StoreAdmin/returns_index'));
    }

    public function store_manager(){
        $orderList = $this->orderModel->where(['store_id'=>$this->store_id])->paginate(10,false,['query' => request()->param()]);
        $page = $orderList->render();

        $this->assign([
            'orderList' => $orderList,
            'page' => $page
        ]);
        return $this->fetch('store_manager');
    }
}